// const API_HOST = 'http://101.42.238.189:8083';
const API_HOST = 'https://www.yecheng-health.com';
/**
 * 路由跳转，主要拦截登录状态
 * @param {*} path 跳转的页面路径
 * @param {*} type 页面跳转类型 navigate/redirect (暂时只考虑这两种)
 * @param {*} requireLogin 是否需要验证登录
 * @param {*} option 页面参数
 */
const goPage = (path,type,requireLogin,option) => {
  let paramsStr = '';
  if(option){
    let keys = Object.keys(option);
    for (let i = 0; i < keys.length; i++) {
      if(i == 0){
        paramsStr += `?${keys[i]}=${option[keys[i]]}`
      }else if(i < keys.length){
        paramsStr += `&${keys[i]}=${option[keys[i]]}`
      }      
    }
  }
  if(!requireLogin){
    if('navigate' === type){
      wx.navigateTo({
        url: API_HOST + path + paramsStr,
      })
    }else{
      wx.redirectTo({
        url: API_HOST + path + paramsStr,
      })
    }
  }else{
    //跳转到登录页面
    wx.navigateTo({
      url: '/pages/login/login.wxml'+`?path=${path}&params=${option}`,
    })
  }
}

//判断是否登录
const isLogin = () =>{
  wx.getStorage('token').then((res)=>{
    if(res.data) {
      return true;
    }else{
      return false;
    }
  });
}

const reqHttp = (url,method,data) => {
  return new Promise((resolve,reject) => {
    wx.showLoading();
    if (method === 'GET') {
      var header = {
        'content-type': "application/x-www-form-urlencoded"
      }
    } else if (method === 'POST') {
      var header = {
        'content-type': 'application/json'
      }
    }
    
    if(url.indexof("valid" > 0)){
      //需要先登录

    }
    wx.request({
      url: API_HOST + url,
      data,
      method,
      header: header,
      timeout: 6000,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 500) {
          wx.showModal({
            title: '提示',
            content: '网络服务异常！',
            showCancel: false
          })
          reject(res);
        } else if (res.statusCode === 200) {
         if (res.data.code === 200) {
            resolve(res);
          } else {
            //业务处理
            reject(res);
          }
        } else if(res.statusCode === 401){//没登录
          //reject(res)
          // 跳转登录
          wx.redirectTo({
            url: '/login/login',
          })
        } else {
          wx.showModal({
            title: '错误信息',
            content: '操作失败！如需帮助请联系技术人员',
            showCancel: false
          })
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showModal({
          title: '错误信息',
          content: '网络不可用，请检查你的网络状态或稍后再试！',
          showCancel: false
        })
        reject(err);
      }
    })
  })
}